package com.liuchuanzheng.lcz_wanandroid.module.detail.viewmodel

import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.LiveEventBus
import com.liuchuanzheng.lcz_wanandroid.R
import com.liuchuanzheng.lcz_wanandroid.base.BaseViewModel
import com.liuchuanzheng.lcz_wanandroid.ext.showToast
import com.liuchuanzheng.lcz_wanandroid.module.common.bus.CollectStatusEvent
import com.liuchuanzheng.lcz_wanandroid.module.history.repository.HistoryRepository
import com.liuchuanzheng.lcz_wanandroid.module.home.bean.Article
import com.liuchuanzheng.lcz_wanandroid.module.home.repository.CollectRepository

/**
 * @author 刘传政
 * @date 2021/9/16 0016 14:44
 * QQ:1052374416
 * 电话:18501231486
 * 作用:
 * 注意事项:
 */
class DetailViewModel : BaseViewModel() {
    val liveData_loading = MutableLiveData<Boolean>()
    private val historyRepository by lazy { HistoryRepository() }
    private val collectRepository by lazy { CollectRepository() }
    fun collect(id: Long) {
        liveData_loading.value = true
        launch(
            workBlock = {
                var result = collectRepository.collect(id)
                handleResult(result,
                    successBlock = {
                        showToast("收藏成功")
                        val event = CollectStatusEvent(id, true)
                        LiveEventBus.get(CollectStatusEvent::class.java).post(event)
                    },
                    failBlock = {
                        showToast("${result.errorMsg}")
                    }
                )
            }, errorBlock = {
                showToast(R.string.network_not_available)
            }, finillyBlock = {
                liveData_loading.value = false
            }
        )
    }

    fun uncollect(id: Long) {
        liveData_loading.value = true
        launch(
            workBlock = {
                var result = collectRepository.uncollect(id)
                handleResult(result,
                    successBlock = {
                        showToast("已取消收藏")
                        val event = CollectStatusEvent(id, false)
                        LiveEventBus.get(CollectStatusEvent::class.java).post(event)
                    },
                    failBlock = {
                        showToast("${result.errorMsg}")
                    }
                )
            }, errorBlock = {
                showToast(R.string.network_not_available)
            }, finillyBlock = {
                liveData_loading.value = false
            }
        )
    }

    fun addReadHistory(article: Article) {
        launch(
            workBlock = {
                historyRepository.addReadHistory(article)
            })
    }
}